#include "MMesh.h"
#include <time.h>

MMesh::MMesh(void)
{
	name="Mesh";
	bNormal = false;
}


MMesh::~MMesh(void)
{

}

MMesh *MMesh::makeMesh(string strFile) {
	MMesh *rt= new MMesh();
	ifstream fin(strFile);
	if(fin.is_open()) {
		string tmp;
		int i = 0;
		while(fin.good()) {
			getline(fin,tmp);
			vector<string> datav;
			istringstream stm(tmp);
			while(getline(stm,tmp,' ')) {
				datav.push_back(tmp);
			}
			if(datav.empty() || !datav[0].compare("#")) {
				continue;
			}
			try{
				if(!datav[0].compare("v")) {
					rt->vertex.push_back(MVertex(atof(datav[1].data()),atof(datav[2].data()),atof(datav[3].data())));
				}
				else if(!datav[0].compare("vt")) {//texture
					rt->texture.push_back(MVertex(atof(datav[1].data()),atof(datav[2].data()),0));
				}
				else if(!datav[0].compare("vn")) {	//normal
					rt->normal.push_back(MVertex(atof(datav[1].data()),atof(datav[2].data()),atof(datav[3].data())));
				}
				else if(!datav[0].compare("f")) {	//poly surface
					vector<TRIPLE> vntriplelist; 
					for(int i = 1; i<datav.size(); i++) {
						vector<string> vntriple;
						istringstream vnstm(datav[i]);
						string strindex;
						TRIPLE triple;
						while(getline(vnstm,strindex,'/')) {
							vntriple.push_back(strindex);
						}
						for(int j=0;j<vntriple.size();j++) {
							triple.index[j] = atoi(vntriple[j].data())-1;
						}
						vntriplelist.push_back(triple);
					}
					rt->poly.push_back(vntriplelist);
				}
				else {
					cout<<"WTF: "<<datav[0]<<endl;
				}
			}
			catch(const runtime_error &e) {

			}
			i++;
		}
		fin.close();
		return rt;
	}
	else {//can not find file
		fprintf(stderr,"Can not open file: %s \n", strFile);
		return NULL;
	}
}

void MMesh::drawShape() {

}

void MMesh::drawMesh(void(*draw_poly)(const vector<MVertex> &v1, int ic),
		void(*drawline)(const MVertex &p1,  const MVertex &p2,int ic)) {
	int icolor = 5;//rand()%8+1;
	vector<MVertex> vlist;
	for(int i = 0; i<poly.size(); i++) {
		vlist.clear();
		for(int j=0; j<poly[i].size();j++) {
			vlist.push_back(vertex[poly[i][j].index[0]]);
			if(drawline && bNormal) {
				drawline(vertex[poly[i][j].index[0]],vertex[poly[i][j].index[0]]+normal[poly[i][j].index[2]]*NORMALEN,1);
			}
		}
		draw_poly(vlist,icolor);
	}
}


void MMesh::incrementSlice() {

}

void MMesh::decrementSlice() {

}

void MMesh::incrementStack() {

}

void MMesh::decrementStack() {

}
